package utils

import (
	"errors"
	"strings"
)

/**
 是否大写字母
 */
func IsUpAlphabetic(c rune) bool {
	return 'A' <= c && c <= 'Z'
}

/**
 是否小写字母
 */
func IsLowerAlphabetic(c rune) bool {
	return 'a' <= c && c <= 'z'
}


/**
 是否是字母 A-Z或a-z
*/
func IsAlphabetic(c rune) bool {
	return  'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'

}



func ToUpperRune(c rune) rune {
	if IsLowerAlphabetic(c) {
		return c - 32
	} else {
		return c
	}

}

func ToLowerRune(c rune) rune {
	if IsUpAlphabetic(c) {
		return c + 32
	} else {
		return c
	}
}

/*
  @param  s  字符串
  @param  startIndex  起始下标(inclue)
  @param  endIndex  结束下标(uninclue)
  @return  string
*/
func Substring(s string, startIndex int, endIndex int) string {

	s0 := []rune(s)
	sLen := len(s0)

	if startIndex > endIndex {
		panic(errors.New("startIndex  large than endIndex"))
	}

	if startIndex < 0 || startIndex >= sLen {
		panic(errors.New("startIndex error"))
	}

	if endIndex < 0 || endIndex >= sLen {
		panic(errors.New("startIndex error"))
	}

	return string(s0[startIndex:endIndex])
}

/*
 驼峰风格转下划线
*/
func HumpStyle2Underline(humpStr string) string {
	if 1 == len(humpStr) {
		return strings.ToLower(humpStr)
	}

	hs := []rune(humpStr)
	hslen := len(hs)
	var underlineStr = make([]rune, hslen, hslen*2)
	underlineStr = append(underlineStr, ToLowerRune(hs[0]))

	i := 1
	for ; i < hslen; i = i + 1 {
		if IsUpAlphabetic(hs[i]) {
			underlineStr = append(underlineStr, '_')
			underlineStr = append(underlineStr, ToLowerRune(hs[i]))
		} else {
			underlineStr = append(underlineStr, hs[i])
		}

	}

	return string(underlineStr)

}